import { PrismaClient } from '@prisma/client';
import type { 
  Product, 
  ProductCategory, 
  CreateProductRequest, 
  UpdateProductRequest,
  CreateProductCategoryRequest,
  UpdateProductCategoryRequest,
  ProductStats,
  PaginatedProducts
} from '../types/product';
import { generateSlug, generateUniqueSlug } from '../utils/slug';

const prisma = new PrismaClient();

export class ProductService {
  // === 用户端接口 ===
  
  // 获取产品列表 (用户端)
  async getProducts(params: {
    page?: number;
    pageSize?: number;
    categoryId?: number;
    sort?: 'latest' | 'popular';
    keyword?: string;
  }): Promise<PaginatedProducts> {
    const { page = 1, pageSize = 10, categoryId, sort = 'latest', keyword } = params;
    const skip = (page - 1) * pageSize;

    // 构建查询条件
    const where: any = {
      status: true,
      publishedAt: { not: null },
      display: true, // 只显示未软删除的数据
    };

    if (categoryId) {
      where.categoryId = categoryId;
    }

    if (keyword) {
      where.OR = [
        { title: { contains: keyword, mode: 'insensitive' } },
        { summary: { contains: keyword, mode: 'insensitive' } },
        { content: { contains: keyword, mode: 'insensitive' } }
      ];
    }

    // 构建排序条件 - 置顶产品优先，然后按其他条件排序
    const orderBy: any = [
      { isTop: 'desc' }, // 置顶产品优先
      sort === 'latest' ? { publishedAt: 'desc' } : 
      sort === 'popular' ? { views: 'desc' } : 
      { publishedAt: 'desc' }
    ];

    // 查询数据
    const [products, total] = await Promise.all([
      prisma.product.findMany({
        where,
        include: {
          category: true,
          user: {
            select: {
              id: true,
              username: true
            }
          }
        },
        orderBy,
        skip,
        take: pageSize
      }),
      prisma.product.count({ where })
    ]);

    return {
      products: products as unknown as Product[],
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  // 获取单个产品详情 (用户端)
  async getProductBySlug(slug: string): Promise<Product | null> {
    const product = await prisma.product.findFirst({
      where: {
        slug,
        display: true, // 只显示未软删除的数据
      },
      include: {
        category: true,
        user: {
          select: {
            id: true,
            username: true
          }
        },
        productComments: {
          where: { status: true },
          orderBy: { createdAt: 'desc' }
        }
      }
    });

    if (product) {
      // 增加浏览量
      await prisma.product.update({
        where: { id: product.id },
        data: { views: { increment: 1 } }
      });
    }

    return product as unknown as Product | null;
  }

  // 获取推荐产品 (用户端)
  async getRecommendProducts(limit: number = 6): Promise<Product[]> {
    const products = await prisma.product.findMany({
      where: {
        status: true,
        isRecommend: true,
        display: true, // 只显示未软删除的数据
      },
      include: {
        category: true,
        user: {
          select: {
            id: true,
            username: true
          }
        }
      },
      orderBy: { createdAt: 'desc' },
      take: limit
    });

    return products as unknown as Product[];
  }

  // 获取置顶产品 (用户端)
  async getTopProducts(limit: number = 6): Promise<Product[]> {
    const products = await prisma.product.findMany({
      where: {
        status: true,
        isTop: true,
        display: true, // 只显示未软删除的数据
      },
      include: {
        category: true,
        user: {
          select: {
            id: true,
            username: true
          }
        }
      },
      orderBy: { createdAt: 'desc' },
      take: limit
    });

    return products as unknown as Product[];
  }

  // 获取产品分类 (用户端)
  async getProductCategories(): Promise<ProductCategory[]> {
    const categories = await prisma.productCategory.findMany({
      where: { status: true },
      orderBy: { sort: 'asc' }
    });

    return categories as ProductCategory[];
  }

  // === 管理端接口 ===

  // 获取产品列表 (管理端)
  async getAdminProducts(params: {
    page?: number;
    pageSize?: number;
    categoryId?: number;
    status?: boolean;
    keyword?: string;
    userId?: number;
    sort?: string;
  }): Promise<PaginatedProducts> {
    const { page = 1, pageSize = 10, categoryId, status, keyword, userId, sort } = params;
    const skip = (page - 1) * pageSize;

    const where: any = {
      display: true, // 只显示未软删除的数据
    };
    if (categoryId) where.categoryId = categoryId;
    if (status !== undefined) where.status = status;
    if (userId) where.userId = userId;
    if (keyword) {
      where.OR = [
        { title: { contains: keyword, mode: 'insensitive' } },
        { content: { contains: keyword, mode: 'insensitive' } },
        { summary: { contains: keyword, mode: 'insensitive' } }
      ];
    }

    const orderBy: any = [
      { isTop: 'desc' }, // 置顶产品优先
      sort === 'latest' ? { createdAt: 'desc' } : 
      sort === 'popular' ? { views: 'desc' } : 
      { createdAt: 'desc' }
    ];

    const [products, total] = await Promise.all([
      prisma.product.findMany({
        where,
        orderBy,
        include: {
          category: true,
          user: {
            select: {
              id: true,
              username: true
            }
          }
        },
        skip,
        take: pageSize
      }),
      prisma.product.count({ where })
    ]);

    return {
      products,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  // 获取单个产品详情 (管理端)
  async getProductById(id: number): Promise<Product | null> {
    const product = await prisma.product.findFirst({
      where: {
        id,
        display: true, // 只显示未软删除的数据
      },
      include: {
        category: true,
        user: {
          select: {
            id: true,
            username: true
          }
        }
      }
    });

    return product;
  }

  // 创建产品
  async createProduct(data: CreateProductRequest, userId: number): Promise<Product> {
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: { username: true }
    });

    if (!user) {
      throw new Error('用户不存在');
    }

    // 查所有已存在slug，生成唯一slug
    const allSlugs = (await prisma.product.findMany({ select: { slug: true } })).map(p => p.slug);
    const slug = generateUniqueSlug(allSlugs);

    const product = await prisma.product.create({
      data: {
        ...data,
        slug,
        author: user.username,
        userId: userId,
        publishedAt: data.status ? new Date() : null
      } as any,
      include: {
        category: true,
        user: {
          select: {
            id: true,
            username: true
          }
        }
      }
    });

    return product;
  }

  // 更新产品
  async updateProduct(id: number, data: UpdateProductRequest): Promise<Product> {
    const existingProduct = await prisma.product.findUnique({
      where: { id }
    });

    if (!existingProduct) {
      throw new Error('产品不存在');
    }

    // 如果标题发生变化，需要重新生成slug
    let slug = existingProduct.slug;
    if (data.title && data.title !== existingProduct.title) {
      const baseSlug = generateSlug(data.title);
      slug = baseSlug;
      let counter = 1;

      while (await prisma.product.findUnique({ 
        where: { slug, NOT: { id } } 
      })) {
        slug = `${baseSlug}-${counter}`;
        counter++;
      }
    }

    // 处理发布时间
    let publishedAt = existingProduct.publishedAt;
    if (data.status && !existingProduct.publishedAt) {
      publishedAt = new Date();
    } else if (!data.status) {
      publishedAt = null;
    }

    const product = await prisma.product.update({
      where: { id },
      data: {
        ...data,
        slug,
        publishedAt
      },
      include: {
        category: true,
        user: {
          select: {
            id: true,
            username: true
          }
        }
      }
    });

    return product;
  }

  // 软删除产品
  async deleteProduct(id: number, deleteBy?: number): Promise<void> {
    await prisma.product.update({
      where: { id },
      data: {
        display: false,
        deleteBy: deleteBy || null,
        deleteAt: new Date(),
      }
    });
  }

  // 获取产品统计
  async getProductStats(): Promise<ProductStats> {
    const [total, published, draft, top, recommend] = await Promise.all([
      prisma.product.count({ where: { display: true } }),
      prisma.product.count({ where: { status: true, publishedAt: { not: null }, display: true } }),
      prisma.product.count({ where: { status: false, display: true } }),
      prisma.product.count({ where: { isTop: true, display: true } }),
      prisma.product.count({ where: { isRecommend: true, display: true } })
    ]);

    return {
      total,
      published,
      draft,
      top,
      recommend
    };
  }

  // === 产品分类管理 ===

  // 获取产品分类列表 (管理端)
  async getAdminProductCategories(): Promise<ProductCategory[]> {
    const categories = await prisma.productCategory.findMany({
      orderBy: { sort: 'asc' }
    });

    return categories as ProductCategory[];
  }

  // 获取单个产品分类 (管理端)
  async getProductCategoryById(id: number): Promise<ProductCategory | null> {
    const category = await prisma.productCategory.findUnique({
      where: { id }
    });

    return category as ProductCategory | null;
  }

  // 创建产品分类
  async createProductCategory(data: CreateProductCategoryRequest): Promise<ProductCategory> {
    const category = await prisma.productCategory.create({
      data: {
        ...data,
        sort: data.sort || 0
      }
    });

    return category as ProductCategory;
  }

  // 更新产品分类
  async updateProductCategory(id: number, data: UpdateProductCategoryRequest): Promise<ProductCategory> {
    const category = await prisma.productCategory.update({
      where: { id },
      data
    });

    return category as ProductCategory;
  }

  // 删除产品分类
  async deleteProductCategory(id: number): Promise<void> {
    // 检查是否有关联的产品
    const productCount = await prisma.product.count({
      where: { categoryId: id }
    });

    if (productCount > 0) {
      throw new Error('该分类下还有产品，无法删除');
    }

    await prisma.productCategory.delete({
      where: { id }
    });
  }
} 